﻿#if LOG
using System;
using System.IO;
using System.Text;

using Common;

namespace TeamIce
{
	public static class Logger
	{
	    private const string FILE_NAME = "botlog.txt";

	    static Logger()
		{
			Enabled = true;
			Log("Game start");
		}

		private static FileStream fileStream;

		public static bool Enabled { get; set; }

        public static string TypeToStr(PlayerType type)
        {
            switch (type)
            {
                case PlayerType.Keeper:
                    return "GK";
                case PlayerType.LeftDefender:
                    return "LD";
                case PlayerType.RightDefender:
                    return "RD";
                case PlayerType.LeftForward:
                    return "LF";
                case PlayerType.CenterForward:
                    return "CF";
                case PlayerType.RightForward:
                    return "RF";
                default:
                    return "??";
            }
        }

		public static void LogTeam(Team team, string teamName)
		{
			Log("\"" + teamName + ":>\"+");
			foreach (Player player in team.Players)
				Log("\"{0:0.00} {1:0.00} {2:0.00} {3:0.00}>\"+//{4} FT: {5} TT: {6}",
				    player.Position.X, player.Position.Y, player.Velocity.X, player.Velocity.Y,
                    TypeToStr(player.PlayerType), player.FallenTimer, player.TackleTimer);
		}

		public static void LogPositions(Vector ballPos, Team myTeam, Team enemyTeam)
		{
			Log("\"ball {0:0.00} {1:0.00}>\"+", ballPos.X, ballPos.Y);
			LogTeam(myTeam, "my");
			LogTeam(enemyTeam, "enemy");
		}

		// ReSharper disable MethodOverloadWithOptionalParameter
		public static void Log(string format, params object[] arg)
			// ReSharper restore MethodOverloadWithOptionalParameter
		{
			Log(string.Format(System.Globalization.CultureInfo.CurrentCulture, format, arg));
		}

		public static void Log(string message)
		{
			if (!Enabled) return;
			if (fileStream == null)
			{
				fileStream = new FileStream(FILE_NAME, FileMode.Create, FileAccess.Write);
			}
			int length = message.IndexOf("\n\r", StringComparison.Ordinal);
			string modifiedMessage = length > 0 ? message.Substring(0, length) : message;

			byte[] byteData = Encoding.ASCII.GetBytes(
				//DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss ") + 
				modifiedMessage + "\n\r");
			if (fileStream != null)
			{
				fileStream.Write(byteData, 0, byteData.Length);
				fileStream.Flush();
			}

			if (length <= 0) return;
			Log(message.Substring(length + 1, message.Length - length - 1));
		}

		public static void Close()
		{
			//fileStream.Close();
		}
	}
}

#endif